package producer

import (
	"easyShop/core/config"
	"encoding/json"
	"fmt"
	"github.com/streadway/amqp"
	"log"
)

func UpdateProductToEs(id int) error {
	uri := config.GetConfig("rabbit.uri").(string)
	exchange := config.GetConfig("app_name").(string)
	queueName := "product_update_event"
	routingKey := "product_update_event"
	content := map[string]interface{}{
		"product_id": id,
	}

	// 建立连接
	connection, err := amqp.Dial(uri)
	if err != nil {
		log.Println("Failed to connect to RabbitMQ:", err.Error())
		return err
	}

	defer connection.Close()
	// 创建一个Channel
	channel, err := connection.Channel()
	if err != nil {
		log.Println("Failed to open a channel:", err.Error())
		return err
	}
	defer channel.Close()

	// 声明exchange
	if err := channel.ExchangeDeclare(
		exchange, //name
		"direct", //exchangeType
		true,     //durable
		false,    //auto-deleted
		false,    //internal
		false,    //noWait
		nil,      //arguments
	); err != nil {
		log.Println("Failed to declare a exchange:", err.Error())
		return err
	}

	// 声明一个queue
	if _, err := channel.QueueDeclare(
		queueName, // name
		true,      // durable
		false,     // delete when unused
		false,     // exclusive
		false,     // no-wait
		nil,       // arguments
	); err != nil {
		log.Println("Failed to declare a queue:", err.Error())
		return err
	}

	// exchange 绑定 queue
	bindErr := channel.QueueBind(queueName, routingKey, exchange, false, nil)
	if bindErr != nil {
		fmt.Print("绑定queue错误")
	}

	// 发送
	messageBody, _ := json.Marshal(content)

	if err = channel.Publish(
		exchange,   // exchange
		routingKey, // routing key
		false,      // mandatory
		false,      // immediate
		amqp.Publishing{
			Headers:         amqp.Table{},
			ContentType:     "text/plain",
			ContentEncoding: "",
			Body:            []byte(messageBody),
			//Expiration:      "60000", // 消息过期时间
		},
	); err != nil {
		log.Println("Failed to publish a message:", err.Error())
		return err
	}

	return nil
}
